﻿using DapperExtensions;
using Interface.Core.Controllers;
using Interface.Core.Utility;
using Interface.Dapper;
using Interface.Mvc.Areas.Scrm.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace Interface.Mvc.Areas.Scrm.Controllers
{
    public class ProductController : CoreController
    {
        /// <summary>
        /// 查询产品列表
        /// url: /scrm/product/query
        /// params: rows, page, categoryid, code, name, exchange, effective
        /// </summary>
        [HttpGet]
        public string Query(int rows, int page, int categoryid, string code, string name, bool? exchange, bool? effective)
        {
            var predicate = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };

            if (categoryid > 0)
            {
                predicate.Predicates.Add(Predicates.Field<ProductInfo>(m => m.CategoryID, Operator.Eq, categoryid));
            }
            if (!string.IsNullOrEmpty(code))
            {
                predicate.Predicates.Add(Predicates.Field<ProductInfo>(m => m.Code, Operator.Eq, code));
            }
            if (!string.IsNullOrEmpty(name))
            {
                predicate.Predicates.Add(Predicates.Field<ProductInfo>(m => m.Name, Operator.Like, "%" + name + "%"));
            }
            if (exchange.HasValue)
            {
                predicate.Predicates.Add(Predicates.Field<ProductInfo>(m => m.Exchange, Operator.Eq, exchange.Value));
            }
            if (effective.HasValue)
            {
                predicate.Predicates.Add(Predicates.Field<ProductInfo>(m => m.Effective, Operator.Eq, effective.Value));
            }

            int count = db.Scrm.Count<ProductInfo>(predicate);

            var list = db.Scrm.GetPage<ProductInfo>(predicate, DapperSort.SortAsc("Sequence"), page, rows);

            return ResultUtility.SuccessResult(data: new { total = count, rows = list });
        }

        /// <summary>
        /// 查询产品列表
        /// url: /scrm/product/newquery
        /// params: rows, page, categoryid, code, name, exchange, effective
        /// </summary>
        [HttpGet]
        public string NewQuery(int rows, int page, int categoryid, string code, string name, bool? exchange, bool? effective)
        {
            StringBuilder sql = new StringBuilder(@"Select t1.ID,t1.Sequence,t1.CategoryID,t1.TypeID,t1.Code,t1.Name,t1.Specification,
            t1.Unit,t1.Price,t1.Exchange,t1.ExPoint,t1.Effective,t1.Cover,t1.Remark,t1.EShopCode
            From Product_Info t1(nolock),Product_Category t2(nolock)
            Where t1.CategoryID=t2.ID ");

            if (categoryid > 0)
            {
                sql.Append("And CHARINDEX(@categoryid,t2.PPath+'|'+CONVERT(varchar(30),t2.ID)+'|')<>0 ");
            }
            if (!string.IsNullOrEmpty(code))
            {
                sql.Append("And t1.Code=@code ");
            }
            if (!string.IsNullOrEmpty(name))
            {
                sql.Append("And t1.Name Like @name ");
            }
            if (exchange.HasValue)
            {
                sql.Append("And t1.Effective=1 ");
            }
            if (effective.HasValue)
            {
                sql.Append("And t1.Exchange=1 ");
            }

            int count = 0;

            var list = db.Scrm.GetPage<dynamic>(sql.ToString(), "*", "Sequence Asc", rows, page, out count, new { categoryid = string.Format("|{0}|", categoryid), code, name = string.Format("%{0}%", name) });

            return ResultUtility.SuccessResult(data: new { total = count, rows = list });
        }

        /// <summary>
        /// 根据编号集合查询产品
        /// url: /scrm/product/getlistbyids
        /// params: ids(1|2)
        [HttpGet]
        public string GetListByIDS(string ids, bool? effective)
        {
            string sql = @"Select ID, Name, Price, ExPoint, Cover From Product_Info(nolock) 
            Where CHARINDEX('|' + CONVERT(varchar(30), ID) + '|',@IDS) > 0";

            IEnumerable<dynamic> list = null;

            if (effective.HasValue)
            {
                sql += "And Effective=@effective";
                list = db.Scrm.Query<dynamic>(sql, new { IDS = string.Format("|{0}|", ids), effective = effective.Value });
            }
            else { list = db.Scrm.Query<dynamic>(sql, new { IDS = string.Format("|{0}|", ids) }); }

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 根据编号查询产品
        /// url: /scrm/product/getbyid
        /// params: id
        [HttpGet]
        public string GetByID(int id)
        {
            var entity = db.Scrm.Get<ProductInfo>(id);

            return ResultUtility.SuccessResult(data: entity);
        }

        /// <summary>
        /// 根据编码查询产品
        /// url: /scrm/product/getbycode
        /// params: code
        [HttpGet]
        public string GetByCode(string code)
        {
            var predicate = Predicates.Field<ProductInfo>(f => f.Code, Operator.Eq, code);

            var entity = db.Scrm.GetList<ProductInfo>(predicate).FirstOrDefault();

            if (entity != null)
            {
                return ResultUtility.SuccessResult(data: entity);
            }

            return ResultUtility.FailureResult("没有找到相应的产品!");
        }

        /// <summary>
        /// 查询产品扩展信息
        /// url: /scrm/product/getextcontent
        /// params: categoryid, code, name
        [HttpGet]
        public string GetExtContent(int productid, string usetype, bool usejson)
        {
            var predicate = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };

            predicate.Predicates.Add(Predicates.Field<ProductInfoExt>(m => m.ProductID, Operator.Eq, productid));
            predicate.Predicates.Add(Predicates.Field<ProductInfoExt>(m => m.UseType, Operator.Eq, usetype));

            var entity = db.Scrm.GetList<ProductInfoExt>(predicate).FirstOrDefault();

            if (usejson)
            {
                if (entity != null)
                {
                    return ResultUtility.SuccessResult(data: entity.Content);
                }
                else { return ResultUtility.FailureResult(); }
            }
            else { return entity != null ? entity.Content : string.Empty; }
        }

        /// <summary>
        /// 根据专区编号查询专区
        /// url: /scrm/product/getzonebyid
        /// params: id
        [HttpGet]
        public string GetZoneByID(int id)
        {
            var entity = db.Scrm.Get<ProductActivityZone>(id);

            if (entity != null)
            {
                return ResultUtility.SuccessResult(data: entity);
            }

            return ResultUtility.FailureResult("没有找到相应的专区!");
        }

        /// <summary>
        /// 根据专区编号查询产品
        /// url: /scrm/product/getbyzoneid
        /// params: top
        /// </summary>
        [HttpGet]
        public string GetByZoneID(int rows, int page, int zoneid)
        {
            string sql = @"Select t1.Sequence,t2.ID,t2.Name,t2.Cover,t2.ExPoint,t2.Price
            From Product_ZoneProduct t1(nolock),Product_Info t2(nolock)
            Where t1.ProductID=t2.ID
            And t2.Exchange=1
            And t2.Effective=1
            And t1.ZoneID=@ZoneID";

            int count = 0;

            var list = db.Scrm.GetPage<dynamic>(sql, "*", "Sequence Asc", rows, page, out count, new { ZoneID = zoneid });

            return ResultUtility.SuccessResult(data: new { total = count, rows = list });
        }

        /// <summary>
        /// 限时兑换
        /// url: /scrm/product/getlimittime
        /// params: top
        /// </summary>
        [HttpGet]
        public string GetLimitTime(int top)
        {
            var today = DateTime.Now.ToString("yyyy-MM-dd");

            string sql = string.Format(@"Select Top {0} t2.ID,t2.Name,t2.Cover,t1.SmileValue,t1.RestCount,t1.LimitEDate
            From Product_LimitProduct t1(nolock),Product_Info t2(nolock)
            Where t1.ProductID=t2.ID
            And t1.LimitTime=1
            And t1.Effective=1
            And t1.LimitBDate<=@Today
            And t1.LimitEDate>=@Today", top);

            var list = db.Scrm.Query<dynamic>(sql, new { today = today });

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 限量兑换
        /// url: /scrm/product/getlimitcount
        /// params: top
        /// </summary>
        [HttpGet]
        public string GetLimitCount(int top)
        {
            string sql = string.Format(@"Select Top {0} t2.ID,t2.Name,t2.Cover,t1.SmileValue,t1.RestCount,t2.Unit
            From Product_LimitProduct t1(nolock),Product_Info t2(nolock)
            Where t1.ProductID=t2.ID
            And t1.LimitTime=0
            And t1.Effective=1", top);

            var list = db.Scrm.Query<dynamic>(sql, new { });

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 根据产品编号获取限时、限量
        /// url: /scrm/product/getlimitbyid
        /// params: productid
        /// </summary>
        [HttpGet]
        public string GetLimitByID(int productid)
        {
            var today = DateTime.Now.ToString("yyyy-MM-dd");

            string sql = @"Select ID,SmileValue,StockCount,RestCount,LimitCount,LimitTime,LimitBDate,LimitEDate,ShareTitle,ShareContent
            From Product_LimitProduct t1(nolock)
            Where LimitTime=1
            And Effective=1
            And LimitBDate<=@Today
            And LimitEDate>=@Today
            And ProductID=@ProductID
            And RestCount>0 
            Union All
            Select ID,SmileValue,StockCount,RestCount,LimitCount,LimitTime,LimitBDate,LimitEDate,ShareTitle,ShareContent
            From Product_LimitProduct t1(nolock)
            Where LimitTime=0
            And Effective=1
            And ProductID=@ProductID 
            And RestCount>0";

            var list = db.Scrm.Query<dynamic>(sql, new { today = today, productid = productid });

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 根据产品编号集合获取限时、限量
        /// url: /scrm/product/getlimitbyids
        /// params: ids 1|2|3
        /// </summary>
        [HttpPost]
        public string GetLimitByIDs(string ids)
        {
            var today = DateTime.Now.ToString("yyyy-MM-dd");

            string sql = @"Select ID,ProductID,SmileValue,StockCount,RestCount,LimitCount,LimitTime,LimitBDate,LimitEDate,ShareTitle,ShareContent
            From Product_LimitProduct t1(nolock)
            Where LimitTime=1
            And Effective=1
            And LimitBDate<=@Today
            And LimitEDate>=@Today
            And CHARINDEX('|'+CONVERT(varchar(30), ProductID)+'|',@IDS)>0
            And RestCount>0 
            Union All
            Select ID,ProductID,SmileValue,StockCount,RestCount,LimitCount,LimitTime,LimitBDate,LimitEDate,ShareTitle,ShareContent
            From Product_LimitProduct t1(nolock)
            Where LimitTime=0
            And Effective=1
            And CHARINDEX('|'+CONVERT(varchar(30), ProductID)+'|',@IDS)>0
            And RestCount>0";

            var list = db.Scrm.Query<dynamic>(sql, new { today = today, IDS = string.Format("|{0}|", ids) });

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 猜你要兑换
        /// url: /scrm/product/getguesslist
        /// params: memberid
        /// </summary>
        [HttpGet]
        public string GetGuessList(int memberid)
        {
            var list = db.Crm.StoredQuery<dynamic>("Scrm_Sp_GuessExchange", new { memberid = memberid }, true, 0);

            return ResultUtility.SuccessResult(data: list);
        }

        /// <summary>
        /// 商品浏览记录
        /// url: /scrm/product/view
        /// params: memberid, productid, viewsource, remark
        /// </summary>
        [HttpPost]
        public string View(int memberid, int productid, string viewsource, string remark)
        {
            string sql = @"Insert Into Member_ProductView(MemberID,ProductID,ViewSource,ViewDate,Remark)
            Values(@MemberID,@ProductID,@ViewSource,GETDATE(),@Remark)";

            bool success = db.Scrm.Execute(sql, new { MemberID = memberid, ProductID = productid, ViewSource = viewsource, Remark = remark }) > 0;

            return ResultUtility.Result(success);
        }

        /// <summary>
        /// 根据产品积分码查询产品条码、名称
        /// url: /scrm/product/getbyjfcode
        /// params: jfcode
        /// </summary>
        [HttpGet]
        public string GetByJfCode(string jfcode)
        {
            string sql = @"Select t2.ProductCode,t2.FullName
            From MCS_AFC.dbo.AFC_ProductCode t1(nolock),CRM_PDT_Product t2(nolock)
            Where t1.CaseID=t2.ID
            And t1.ProductCode=@JfCode";

            var product = db.Erp.Query<dynamic>(sql, new { jfcode }).FirstOrDefault();

            return ResultUtility.SuccessResult(data: product);
        }
    }
}